package cn.simon.controller;

import cn.simon.model.Cart;
import cn.simon.model.Goods;
import cn.simon.model.Orders;
import cn.simon.model.Seller;
import cn.simon.service.CartService;
import cn.simon.service.GoodsService;
import cn.simon.service.OrdersService;
import cn.simon.service.SellerService;
import lombok.extern.java.Log;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.Date;

/**
 * 本控制器负责商品详情页相关请求和响应
 *
 * @author Kinfer
 * @date 2022/10/28
 */
@Log
@Controller
@RequestMapping("/goodsDetail")
public class GoodsDetailController {
    @Autowired
    private GoodsService goodsService;
    @Autowired
    private SellerService sellerService;

    @Autowired
    private OrdersService ordersService;

    @Autowired
    private CartService cartService;

    /**
     * 响应请求，跳转到商品详情页
     *
     * @param goodsId
     * @param model
     * @return
     * @author Kinfer
     * @date 2022/10/28
     */
    @GetMapping("")
    public String showGoodsDetail(Integer goodsId, Model model) {
        Goods goods = goodsService.findByGoodsId(goodsId);
        Seller seller = sellerService.getSellerById(goods.getSellerId());
        model.addAttribute("goods", goods);
        model.addAttribute("seller", seller);
        return "goodsDetail";
    }

    /**
     * 生成初始订单
     *
     * @param goodsId
     * @return
     * @author Kinfer
     * @date 2022/10/28
     */
    @GetMapping("/addOrder")
    public String addOrder(Integer goodsId) {
        // TODO: 2022/10/28 需要获取用户id
        int userId = 1;

        Goods goods = goodsService.findByGoodsId(goodsId);

        Orders order = Orders.builder().userId(userId)
                .orderPrice(goods.getGoodsPrice())
                .orderCreateTime(new Date())
                .addressId(0)   // 此时未选择地址，地址id为0
                .orderState(1)
                .goodsId(goodsId)
                .orderGoodsNumber(1).build();   // 未选择数量，初始为1
        ordersService.addOrder(order);
        return null;
    }

    /**
     * 添加商品到购物车
     *
     * @param goodsId
     * @return
     * @author Kinfer
     * @date 2022/10/31
     */
    @GetMapping("/addCart")
    public String addCart(Integer goodsId) {
        // TODO: 2022/10/28 需要获取用户id
        int userId = 1;

        Cart cart = Cart.builder().userId(userId)
                .goodsId(goodsId)
                .cartGoodsNumber(1).build();    // 加购初始数量为1

        cartService.addCart(cart);
        return "redirect:?goodsId=" + goodsId;
    }
}
